package cmpp.validate;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import com.demo.jfinal.model.ApiDownstream;
import com.google.common.base.Charsets;

import cmpp.pdu.Connect;

/**
 * 验证工具类：账号密码，ip
 */
public class ClientValidateUtil {

	/**
	 * 账号密码验证
	 */
	public static boolean authenticateClient(byte[] authenticatorSource, Connect con) {

//		// 验证账号密码
		String clientUser = con.getClientId();
		String clientPsd = "";

		// 获取该客户信息
		ApiDownstream apidownconfig = ApiDownstream.dao
				.findFirst("select * from sms_api_downstream_config s where s.APPKEY = ? ", clientUser);
		if (apidownconfig != null) {
			clientPsd = apidownconfig.getStr("SECURTY");
		} else {
			return false;
		}
		return Arrays.equals(getAuthString(clientUser, clientPsd, con.getTimeStamp()), authenticatorSource);
//		return true;

	}

	/**
	 * 用户鉴权数据生成
	 *
	 * @param user
	 *            协议中 Source_Addr
	 * @param passwd
	 *            协议中 shared secret
	 * @param timeStamp
	 *            整型时间，例如『708101023』
	 * @return
	 */
	public static byte[] getAuthString(String user, String passwd, int timeStamp) {
		String timeStr = String.valueOf(timeStamp);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 10 - timeStr.length(); i++) {
			sb.append("0");
		}
		sb.append(timeStr);
		return getAuthString(user, passwd, sb.toString());
	}

	public static byte[] getAuthString(String user, String passwd, String timeStamp) {
		byte[] bytes = new byte[user.length() + 9 + passwd.length() + timeStamp.length()];
		System.arraycopy(user.getBytes(Charsets.US_ASCII), 0, bytes, 0, user.length());
		System.arraycopy(passwd.getBytes(Charsets.US_ASCII), 0, bytes, user.length() + 9, passwd.length());
		System.arraycopy(timeStamp.getBytes(Charsets.US_ASCII), 0, bytes, user.length() + 9 + passwd.length(), 10);
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return md.digest(bytes);
	}
}
